package com.chen.nongansampling.fragment.ui.sample;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.chen.nongansampling.AddTypeActivity;
import com.chen.nongansampling.Application;
import com.chen.nongansampling.LocationUtils;
import com.chen.nongansampling.R;
import com.chen.nongansampling.adapter.ListViewItemAdapter;
import com.chen.nongansampling.adapter.ListviewTextAdapter;
import com.chen.nongansampling.adapter.PictureAddGridAdapter;
import com.chen.nongansampling.app.BaseApplication;
import com.chen.nongansampling.bean.OperatingBean;
import com.chen.nongansampling.bean.SimpleRequest;
import com.chen.nongansampling.bean.sample.FileListBean;
import com.chen.nongansampling.bean.sample.SampleCallbackData;
import com.chen.nongansampling.bean.sample.TypeList;
import com.chen.nongansampling.bean.sample.TypeListItem;
import com.chen.nongansampling.bean.sample.insert.SamplingInformation;
import com.chen.nongansampling.bean.sample.insert.SamplingRequset;
import com.chen.nongansampling.bean.tanchubean;
import com.chen.nongansampling.bean.ui.ListviewBean;
import com.chen.nongansampling.custom.CustomScrollGridView;
import com.chen.nongansampling.fragment.LabelPrintedFragment;
import com.chen.nongansampling.model.CallbackData;
import com.chen.nongansampling.model.Market;
import com.chen.nongansampling.presenter.SamplePresenter;
import com.chen.nongansampling.presenterView.SampleView;
import com.chen.nongansampling.utils.CommandPhotoUtil;
import com.chen.nongansampling.utils.ImageUtil;
import com.chen.nongansampling.utils.PhotoBitmapUtil;
import com.chen.nongansampling.utils.PhotoSystemOrShoot;
import com.chen.nongansampling.view.LinePathView;
import com.chen.nongansampling.viewModel.SamplingViewModel;
import com.haoyd.printerlib.GPS.LocationService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.chen.nongansampling.MainActivity.cunchu;
import static com.chen.nongansampling.MainActivity.yx;

public class SampleFragment extends Fragment implements SampleView {

    private String shichang;
    private String leibie;
    private String jiancexiangmu;
    private  String jiancefangfa;
    private int jumpid;
    private int leibiebiaoshi;
    private int jiancebiaoshi;
    private  String typename;

    /**
     * 存放图片的容器
     */
    private CustomScrollGridView mGridView;

    /**
     * GridView适配器
     */
    private PictureAddGridAdapter gridAdapter;

    /**
     * 管理图片操作
     */
    private CommandPhotoUtil commandPhoto;

    /**
     * 选择图片来源
     */
    private PhotoSystemOrShoot selectPhoto;

    public int a=0;
    private SamplePresenter samplePresenter=new SamplePresenter(getContext());


    static List<Market> marketList=new ArrayList<>();  //市场列表
    static List<OperatingBean> operatorList=new ArrayList<>();
    private CallbackData<List<TypeList>> typelist;
    private CallbackData<List<TypeList>> typelistDeTypeAndName;
    public String smilt;
    public String num;
    private List<TypeListItem> typelistname=new ArrayList<>();

    private List<TypeListItem> typelistnametDeTypeAndName=new ArrayList<>();


    private SamplingInformation samplingInformation=new SamplingInformation();      //采样信息
    private SamplingRequset samplingRequset=new SamplingRequset();        //采样请求

    private PopupWindow popupSignWindow;      //签名弹窗
    private int jingyingbiaoshi=0;
    private  View  view;
    private View mSignView;
    private Bitmap signBitmap;
    public static CallbackData<List<TypeList>> typelistAdd;
    public String jingdu;
    public String weidu;
    public String xiangxidizhi;
    public String jingyinghu;
    public String xiangpinmingcheng;
    @BindView(R.id.sample)
    LinearLayout linearLayout;
    public LayoutInflater inflaters;
    private LocationService locationService;
    public Vibrator mVibrator;
    private SamplingViewModel mViewModel;
    public static SampleFragment newInstance() {
        return new SampleFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        inflaters=inflater;
        view=inflater.inflate(R.layout.sample_fragment, container, false);
        mSignView= inflater.inflate(R.layout.popup_sign_window, null);
        ImageButton imageButton=getActivity().findViewById(R.id.add_sample);
        imageButton.setVisibility(View.INVISIBLE);
        ButterKnife.bind(this, view);
        //      return inflater.inflate(R.layout.sample_fragment, container, false);



        return view;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        TextView title = getActivity().findViewById(R.id.sample_tool_bar_name);
//        getActivity().setSupportActionBar(toolbar);
//        getSupportActionBar().setDisplayShowTitleEnabled(false);//隐藏标题
        toolbar.setNavigationIcon(R.mipmap.back_white);//加载图标
        title.setText("样品采样");
        title.setGravity(Gravity.CENTER);
        ImageButton imageButton = getActivity().findViewById(R.id.add_sample);
        imageButton.setVisibility(View.VISIBLE);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typelistAdd=typelist;
                Log.d("2333", "qqqq");
                Intent intent = new Intent(getActivity(), AddTypeActivity.class);
                startActivity(intent);

            }
        });
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {   //为图标设置监听器
            @Override
            public void onClick(View v) {

                getActivity().onBackPressed();
            }
        });

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        locationService = new LocationService(getActivity().getApplicationContext());
        mVibrator =(Vibrator)getActivity().getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
        SDKInitializer.initialize(getActivity().getApplicationContext());
        SDKInitializer.setCoordType(CoordType.BD09LL);
        locationService.registerListener(mListener);
        //注册监听
        int type = getActivity().getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
            //wxs增加判断
            if(!locationService.isStart()) {
                locationService.start();
            }
        } else if (type == 1) {
            if(!locationService.isStart()) {
                locationService.start();
            }
        }
        //System.out.println("经纬度经纬度经纬度"+getActivity());
    }

    @BindView(R.id.sample_text_listview) ListView textlistView;
    //   @BindView(R.id.add_picture) ImageView addPicture;
    @BindView(R.id.sample_text_listview1) ListView textlistView1;
    @Override
    public void onDetach() {
        super.onDetach();
        //wxs添加
        mCtx=null;


        Log.d("onDetach","onDetach");
    }

    @Override
    public void onDestroyView() {
        //wxs添加销毁textlistView1
        //((ViewGroup) textlistView1.getParent()).removeView(textlistView1);//remove View
        super.onDestroyView();
        Log.d("onDetach","onDestroyView");

    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("onDetach","onPause");

    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d("onDetach","onStop");

    }

    @OnClick(R.id.continueAdd)
    public void continueAdd(){
        try {
            if(xiangxidizhi!=null){
                jumpid=0;
                String jingweidu=LocationUtils.getInstance().getLocations(getContext());
                samplingRequset.setJingdu(jingdu);
                samplingRequset.setWeidu(weidu);

                samplingRequset.setAccountPkId(BaseApplication.getAccount().getPkId());
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
                samplingInformation.setSampleNumber(df.format(new Date()) + getTreeNumRandom());
                SimpleDateFormat df2 = new SimpleDateFormat("");//设置日期格式
                samplingInformation.setSamplingTime(df2.format(new Date()));
                samplingInformation.setSampleAccountId(BaseApplication.getAccount().getPkId());
                samplingInformation.setAddress(xiangxidizhi);
                signImageView.setDrawingCacheEnabled(true);
                if(a==1){
                    Bitmap bitmap= Bitmap.createBitmap(signImageView.getDrawingCache());
                    samplingInformation.setAutograph(ImageUtil.toBase64String(bitmap));
                    signImageView.setImageBitmap(bitmap);
                    a=0;
                }else{
                    samplingInformation.setAutograph("");
                }
                signImageView.setDrawingCacheEnabled(false);
                List<FileListBean> listBeans = new ArrayList<>();
                for (int i = 0; i < gridAdapter.getCount() - 1; i++) {
                    Bitmap b = PhotoBitmapUtil.getCompressPhoto((String) gridAdapter.getItem(i));
                    FileListBean f = new FileListBean();
                    f.setBase64Str(ImageUtil.toBase64String(b));
                    f.setType("jpg");
                    listBeans.add(f);
                }
                samplingRequset.setFileList(listBeans);
                Bitmap b = PhotoBitmapUtil.getCompressPhoto((String) gridAdapter.getItem(0));
                samplingRequset.setSamplingInformation(samplingInformation);
                samplePresenter.getInsertSamplingResponseInfo(samplingRequset);

                Toast.makeText(getContext(),"提交成功",Toast.LENGTH_LONG).show();
                initListView(1);
                updateGps();
                mSignView= inflaters.inflate(R.layout.popup_sign_window, null);
                signBitmap= BitmapFactory.decodeResource(this.getContext().getResources(),R.mipmap.add_picture);
                signImageView.setImageBitmap(signBitmap);
            }else{
                Toast.makeText(getContext(),"请打开定位自动获取所在地后在提交",Toast.LENGTH_LONG).show();
            }
        }catch (Exception e)
        {
            if(xiangxidizhi==null){
                Toast.makeText(getContext(),"请打开定位自动获取所在地后在提交",Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getContext(),"信息填写不完整",Toast.LENGTH_LONG).show();
            }
        }

    }
    @OnClick(R.id.submit)
    public void onClick(){
//if (signImageView.getDrawingCache()!=null)
//{
        try {
            jumpid=1;
            //wxs修改
            String aaa=samplingInformation.getAddress();

            if(xiangxidizhi!=null){
                samplingRequset.setJingdu(jingdu);
                samplingRequset.setWeidu(weidu);

                samplingRequset.setAccountPkId(BaseApplication.getAccount().getPkId());
//    samplingRequset.setDeTypeId("1");
//    samplingRequset.setDeMethoodPkID("1");

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式

//   samplingInformation.setSampleNumber(TimeFonew Date().getTime()parse().ToString("yyyyMMdd") + getTreeNumRandom(););
                samplingInformation.setSampleNumber(df.format(new Date()) + getTreeNumRandom());
                samplingInformation.setAddress(xiangxidizhi);
                SimpleDateFormat df2 = new SimpleDateFormat("");//设置日期格式
                samplingInformation.setSamplingTime(df2.format(new Date()));
                samplingInformation.setSampleAccountId(BaseApplication.getAccount().getPkId());
//    samplingInformation.setSampleType("1");
//    samplingInformation.setOperatingHouseholdId("1");
//    samplingInformation.setSampleAccountId("1");
                //   samplingInformation.setAutograph(ImageUtil.bitmapToBase64(signBitmap));


                signImageView.setDrawingCacheEnabled(true);

                if(a==1){
                    Bitmap bitmap= Bitmap.createBitmap(signImageView.getDrawingCache());
                    samplingInformation.setAutograph(ImageUtil.toBase64String(bitmap));
                    signImageView.setImageBitmap(bitmap);
                    a=0;
                }else{
                    samplingInformation.setAutograph("");
                }

                signImageView.setDrawingCacheEnabled(false);

                //samplingInformation.setAutograph(ImageUtil.toBase64String(signBitmap));

                List<FileListBean> listBeans = new ArrayList<>();

                for (int i = 0; i < gridAdapter.getCount() - 1; i++) {
                    Bitmap b = PhotoBitmapUtil.getCompressPhoto((String) gridAdapter.getItem(i));
                    FileListBean f = new FileListBean();
                    f.setBase64Str(ImageUtil.toBase64String(b));
                    f.setType("jpg");
                    listBeans.add(f);
                }
                samplingRequset.setFileList(listBeans);
//    Log.d("base64",ImageUtil.toBase64String(signBitmap));
                //  samplingInformation.setAutograph("");
                //  ViewH =gridAdapter.getItem(0);
                Bitmap b = PhotoBitmapUtil.getCompressPhoto((String) gridAdapter.getItem(0));
                // samplingInformation.setSamplePhoto(ImageUtil.bitmapToBase64(b));
                //   img.setImageBitmap(PhotoBitmapUtil.getCompressPhoto(imageItemData.get(position)));
                samplingRequset.setSamplingInformation(samplingInformation);
                samplePresenter.getInsertSamplingResponseInfo(samplingRequset);
            }else{
                Toast.makeText(getContext(),"请打开定位自动获取所在地后在提交",Toast.LENGTH_LONG).show();
            }
        }catch (Exception e)
        {
            if(xiangxidizhi==null){
                Toast.makeText(getContext(),"请打开定位自动获取所在地后在提交",Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getContext(),"信息填写不完整",Toast.LENGTH_LONG).show();
            }

        }


//}else
//{
//    Toast.makeText(getContext(),"请将信息填写完整",Toast.LENGTH_LONG).show();
//}
    }

    public String getTreeNumRandom()
    { int iResult;
        iResult = (int)(Math.random()*900)+100;        //Response.Write(iResult.ToString());
        return iResult+"";
    }


    @BindView(R.id.add_sign)
    ImageView signImageView;


    @OnClick(R.id.add_sign)
    public void onSign(){
        popupSignWindow= new PopupWindow(getContext());
        //  mSignView= Inflater.inflate(R.layout.popup_select_way_photo, null);

        ColorDrawable dw = new ColorDrawable(0x00000000);
        popupSignWindow.setBackgroundDrawable(dw);
        popupSignWindow.setContentView(mSignView);
        //   popupSignWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);

        popupSignWindow.setWidth(900);

        popupSignWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);

        //popupSignWindow.setHeight(400);
        popupSignWindow.setAnimationStyle(R.style.popup_select_way);
        popupSignWindow.setFocusable(true);


        popupSignWindow.showAtLocation(getView(), Gravity.CENTER, 0, 0);

        View view=popupSignWindow.getContentView();

        Button signSave=view.findViewById(R.id.sign_save);
        Button signDel=view.findViewById(R.id.sign_clear);
        final LinePathView linePathView=view.findViewById(R.id.sign_view);

        signDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                linePathView.clear();
                a=0;
            }
        });

        signSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signBitmap=  linePathView.saveToBitmap(true,1);
                a=1;
//            signBitmap=  linePathView.getBitMap();

                signImageView.setImageBitmap(signBitmap);
                popupSignWindow.dismiss();


            }
        });
    }
//    @OnClick(R.id.sign_save)
//    public void onSignSave() {
//    }
//    LinePathView linePathView;
//
//    @OnClick(R.id.sign_clear)
//    public void onSignClear() {
//   //     @BindView(R.id.sign_view)
//         linePathView=getActivity().findViewById(R.id.sign_view);
//        linePathView.clear();
//    }



//    @BindView(R.id.sample_iamge_listview) ListView imagelistView;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(SamplingViewModel .class);

       if(cunchu.getKEY()==4){
           initListView(cunchu.getKEY());
       }else{
           initListView(0);
       }

        updateGps();


        // TODO: Use the ViewModel

    }

@Override
public void onStart(){
    super.onStart();

}
    @Override
    public void onResume() {
        super.onResume();

        samplePresenter.BindPresentView(this);
        samplePresenter.onCreate();
        initRequest();

        //wxs修改
        updateGps();

//        if (cunchu.getBiaoshi()==1) {
//
//            samplingInformation.setOperatingHouseholdId(cunchu.getJingyinghuid());
//            jingyinghu=cunchu.getJingyinghuname();
//            samplingRequset.setDeMethoodPkID(cunchu.getJiancefangfaid());
//            jiancefangfa=cunchu.getJiancefangfaname();
//            samplingRequset.setDeTypeId(cunchu.getJiancetypeid());
//            jiancexiangmu=cunchu.getJiancetypename();
//            samplingInformation.setSampleAccountId(cunchu.getYangpinid());
//            xiangpinmingcheng=cunchu.getYangpinname();
//            samplingInformation.setSampleType(cunchu.getYangpintypeid());
//            leibie=cunchu.getYangpintypename();
//            num=cunchu.getShichangid();
//            shichang=cunchu.getShichangname();
//
//        }
    }

    private void initUI() {
        mGridView = (CustomScrollGridView) getActivity().findViewById(R.id.gv_all_photo);

    }

    /**
     * 实例化组件
     */
    private void addPlus() {
        String kongImage=null;
        gridAdapter = new PictureAddGridAdapter(view.getContext(), 12,kongImage);
        mGridView.setAdapter(gridAdapter);

        //   getActivity().getSupportFragmentManager().saveFragmentInstanceState(SampleFragment.newInstance());
        // 选择图片获取途径
        selectPhoto = new PhotoSystemOrShoot(view.getContext()) {
            @Override
            public void onStartActivityForResult(Intent intent, int requestCode) {

                if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                    Uri contentUri = FileProvider.getUriForFile(context,"com.skyrin.bingo.fileprovider",apkFile);
//                    intent.setDataAndType(contentUri,"application/vnd.android.package-archive");
                    startActivityForResult(intent, requestCode);

                }else {
                    //        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    intent.setDataAndType(
//                            Uri.fromFile(apkFile),
//                            "application/vnd.android.package-archive");
                    startActivityForResult(intent, requestCode);

                }

            }
        };
        commandPhoto = new CommandPhotoUtil(getContext(), mGridView, gridAdapter, selectPhoto);
    }


    public void updateGps(){
        ListviewBean<String> list7=new ListviewBean();
        ListviewBean<String> list8=new ListviewBean();
        list7.setName("经纬度数");
        list7.setImageSrc(R.mipmap.jingweidu);
        list8.setName("所在位置");
        list8.setImageSrc(R.mipmap.weizhi);
        if(xiangxidizhi!=null){
            //找到坐标
            list7.setData("经度:"+jingdu+"纬度:"+weidu);
            list8.setData(xiangxidizhi);
            //停止监听
            //locationService.stop();
            if(!locationService.isStart()) {
                locationService.start();
            }
        }
        else {
            //没找到坐标
            list7.setData("无");
            list8.setData("无");
        }

        List<ListviewBean> listLocation=new ArrayList<>();
        listLocation.add(list7);
        listLocation.add(list8);
        //textlistView1.setAdapter(null);

        //清空
        //List<ListviewBean> list4Clear=new ArrayList<>();
        //ListviewTextAdapter theAdapter4Clear=new ListviewTextAdapter(list4Clear,getContext(),false);
        //textlistView1.setAdapter(theAdapter4Clear);
        //填充
        //ListAdapter theNewAdapter;

        ListviewTextAdapter theAdapter=new ListviewTextAdapter(listLocation,theActivity,false);
        //ListviewTextAdapter theAdapter=new ListviewTextAdapter(listLocation, (Context) Application.theLocContext ,false);
        //ListviewTextAdapter theAdapter=new ListviewTextAdapter(listLocation, getActivity().getApplicationContext() ,false);
        textlistView1.setAdapter(theAdapter);
        theAdapter.notifyDataSetChanged();
        textlistView1.invalidateViews();
        //textlistView1.setAdapter(new ListviewTextAdapter(list,getContext(),false));
        //String theAdd = samplingInformation.getAddress();
    }



    public void initListView(int nums){
        //    listView=getView().findViewById(R.id.sample_text_listview);
        ListviewBean<String> list1=new ListviewBean();
        list1.setData("请选择");
        list1.setImageSrc(R.mipmap.shichangname);
        list1.setName("市场名称");
        list1.setRedStar(true);
        if(nums==1){
            jingdu=null;
            weidu=null;
            xiangxidizhi=null;
            list1.setData(shichang);
            //wxs增加判断
            if(!locationService.isStart()) {
                locationService.start();
            }
        }
        if(nums==2){
            list1.setData(shichang);
            jingyinghu="请选择";
            leibie="请选择";
            jiancexiangmu="请选择";
            xiangpinmingcheng="请选择";
            smilt=null;
            samplingInformation.setOperatingHouseholdId(null);
            samplingInformation.setSampleName(null);

            typelistnametDeTypeAndName=null;
        }

        ListviewBean<String> list2=new ListviewBean();
        list2.setData("请选择");
        list2.setImageSrc(R.mipmap.listview_text_operator);
        list2.setName("经营户");
        list2.setRedStar(true);



        ListviewBean<String> list3=new ListviewBean();
        list3.setData("请选择");
        list3.setImageSrc(R.mipmap.sample_category);
        list3.setName("样品类别");
        list3.setRedStar(true);


        ListviewBean<String> list4=new ListviewBean();
        list4.setData("请选择");
        list4.setImageSrc(R.mipmap.listview_sample_name);
        list4.setName("样品名称");
        list4.setRedStar(true);


        ListviewBean<String> list5=new ListviewBean();
        list5.setData("请选择");
        list5.setImageSrc(R.mipmap.listview_text_test_type);
        list5.setName("检测项目");

        ListviewBean<String> list6=new ListviewBean();
        list6.setData("请选择");
        list6.setImageSrc(R.mipmap.listview_text_test_method);
        list6.setName("检测方法");

        if(nums==3){
            samplingInformation.setSampleName(null);
            samplingInformation.setOperatingHouseholdId(null);
            list1.setData(shichang);
            list3.setData(leibie);
            list5.setData(jiancexiangmu);
            list6.setData(jiancefangfa);
            jingyinghu="请选择";
            //jiancexiangmu="请选择";
            xiangpinmingcheng="请选择";

        }

        if(nums==4){
            if(!TextUtils.isEmpty(shichang)){
                list1.setData(shichang);
            }
            if(!TextUtils.isEmpty(jingyinghu)){
                list2.setData(jingyinghu);
            }

            if(!TextUtils.isEmpty(leibie)){
                list3.setData(leibie);
            }
            if(!TextUtils.isEmpty(xiangpinmingcheng)){
                list4.setData(xiangpinmingcheng);
            }
            if(!TextUtils.isEmpty(jiancexiangmu)){
                list5.setData(jiancexiangmu);
            }
            if(!TextUtils.isEmpty(jiancefangfa)){
                list6.setData(jiancefangfa);
            }

        }


//        ListviewBean<Bitmap> list6=new ListviewBean();
//        Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher, null);
//        list6.setData(bitmap);
//        list6.setImageSrc(R.mipmap.listview_text_test_method);
//        list6.setName("采样照片");
//        list6.setComplicated(true);



        List<ListviewBean> list=new ArrayList<>();
        list.add(list1);
        list.add(list3);
        list.add(list2);

        list.add(list4);
        list.add(list5);
        list.add(list6);

        textlistView.setAdapter(new ListviewTextAdapter(list,getContext(),false));


        textlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position)
                {
                    case 0:{


                        if (marketList.size()!=0) {
                            LayoutInflater inflater = LayoutInflater.from(getContext());
                            View layout = inflater.inflate(R.layout.edit_select, null);
                            final EditText edit = (EditText)layout.findViewById(R.id.listview_edit_data);
                            final TextView title = (TextView)layout.findViewById(R.id.listview_title_name);
                            edit.setHint("请输入菜市场名称");
                            title.setText("请选择市场");
                            String s[]=new String[marketList.size()];
                            List<tanchubean> list=new ArrayList<>();
                            for (int i=0;i<marketList.size();i++)
                            {
                                s[i]=marketList.get(i).getName();
                                tanchubean<String> list1=new tanchubean();
                                list1.setName(marketList.get(i).getName());
                                list.add(list1);
                            }
                            ListViewItemAdapter adapter = new ListViewItemAdapter(getContext(),list);
                            AlertDialog dialogs = new AlertDialog.Builder(getContext())
                                    .setCustomTitle(layout)
                                    //.setView(list)
                                    .setPositiveButton("搜索市场",null)
                                    .setAdapter(adapter, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();

                                    TextView t = view.findViewById(R.id.listview_text_data);
                                    t.setText(marketList.get(which).getName());
                                    t.setTextColor(Color.BLACK);
                                    num=marketList.get(which).getPkId();
                                    shichang=marketList.get(which).getName();
                                    jingyingbiaoshi=1;
                                    if(jingyingbiaoshi==1){
                                        initListView(2);
                                    }
                                }
                            }).create();
                            dialogs.show();
                            // 通过Activity类中的getWindowManager()方法获取窗口管理，再调用getDefaultDisplay()方法获取获取Display对象
                            Display display = getActivity().getWindowManager().getDefaultDisplay();
                            // 方法一(推荐使用)使用Point来保存屏幕宽、高两个数据
                            Point outSize = new Point();
                            // 通过Display对象获取屏幕宽、高数据并保存到Point对象中
                            display.getSize(outSize);
                            // 从Point对象中获取宽、高
                            int x = (new Double(outSize.x*0.9)).intValue();
                            int y = (new Double(outSize.y*0.9)).intValue();

                            dialogs.getWindow().setLayout(x,y);
                            //弹出对话框时需要点击输入框才能弹出软键盘
                            dialogs.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                            dialogs.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(13);
                            Drawable dr = getActivity().getResources().getDrawable(R.drawable.login_btn_selector); //取得图片资源
                            dialogs.getButton(AlertDialog.BUTTON_POSITIVE).setBackground(dr);
                            LinearLayout.LayoutParams PositiveButton =
                                    (LinearLayout.LayoutParams)  dialogs.getButton(DialogInterface.BUTTON_POSITIVE).getLayoutParams();
                            PositiveButton.height = (new Double(outSize.x*0.12)).intValue();
                            PositiveButton.width = (new Double(outSize.x*0.3)).intValue();
                            //设置文字居中
                            PositiveButton.gravity = Gravity.CENTER;
                            PositiveButton.setMargins(new Double(outSize.x-outSize.x*0.3).intValue()/2,
                                    20, new Double(outSize.x-outSize.x*0.3).intValue()/2, 20);
                            dialogs.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    if (!TextUtils.isEmpty(edit.getText().toString())) {
                                            ArrayList<String> strlist = new ArrayList<String>();
                                        ArrayList<Market> marketLists = new ArrayList<Market>();
                                        List<tanchubean> list=new ArrayList<>();
                                        for (int i = 0; i < marketList.size(); i++) {
                                            if(marketList.get(i).getName().indexOf(edit.getText().toString()) != -1){
                                                strlist.add(marketList.get(i).getName());
                                                marketLists.add(marketList.get(i));
                                                tanchubean<String> list1=new tanchubean();
                                                list1.setName(marketList.get(i).getName());
                                                list.add(list1);
                                            }
                                        }
                                        String s[] = (String[]) strlist.toArray(new String[strlist.size()]);
                                        ListViewItemAdapter adapter = new ListViewItemAdapter(getContext(),list);

                                        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext())
                                                .setAdapter(adapter, new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.dismiss();
                                                        dialogs.dismiss();
                                                        TextView t = view.findViewById(R.id.listview_text_data);
                                                        t.setText(marketLists.get(which).getName());
                                                        t.setTextColor(Color.BLACK);
                                                        num=marketLists.get(which).getPkId();
                                                        shichang=marketLists.get(which).getName();
                                                        jingyingbiaoshi=1;
                                                        if(jingyingbiaoshi==1){
                                                            initListView(2);
                                                        }
                                                    }
                                                });
                                        dialog.create().show();

                                    }

                                }
                            });
                        }

                    }break;
                    case 2:{

                        if (num!=null) {
                            if(smilt!=null){
                            if (operatorList != null && operatorList.size() != 0) {
                                LayoutInflater inflater = LayoutInflater.from(getContext());
                                View layout = inflater.inflate(R.layout.edit_select, null);
                                final EditText edit = (EditText)layout.findViewById(R.id.listview_edit_data);
                                final TextView title = (TextView)layout.findViewById(R.id.listview_title_name);
                                edit.setHint("请输入经营户");
                                title.setText("请选择经营户");
                                ArrayList<String> strlist = new ArrayList<String>();
                                ArrayList<OperatingBean> operatorLists = new ArrayList<OperatingBean>();
                                List<tanchubean> list=new ArrayList<>();
                                for (int i = 0; i < operatorList.size(); i++) {
                                    if(operatorList.get(i).getMarketId().equals(num)){
//                                System.out.println("菜市场id:"+operatorList.get(i).getMarketId());
//                                System.out.println("菜市场id:"+num);
//                                System.out.println("人员名:"+operatorList.get(i).getOperatingHouseholds());i
                                        if(operatorList.get(i).getName().indexOf(leibie)!= -1){
                                            strlist.add(operatorList.get(i).getOperatingHouseholds()+"("+operatorList.get(i).getBoothNumber()+")");
                                            operatorLists.add(operatorList.get(i));
                                            tanchubean<String> list1=new tanchubean();
                                            list1.setName(operatorList.get(i).getOperatingHouseholds()+"("+operatorList.get(i).getBoothNumber()+")");
                                            list.add(list1);
                                        }

                                    }
                                }
                                ListViewItemAdapter adapter = new ListViewItemAdapter(getContext(),list);
                                String s[] = (String[]) strlist.toArray(new String[strlist.size()]);
                                AlertDialog dialogs = new AlertDialog.Builder(getContext())
                                        .setCustomTitle(layout)
                                        //.setView(list)
                                        .setPositiveButton("搜索经营户或摊位号",null)
                                        .setAdapter(adapter, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        TextView t = view.findViewById(R.id.listview_text_data);
                                        t.setTextColor(Color.BLACK);
                                        t.setText(operatorLists.get(which).getOperatingHouseholds());
                                        jingyinghu=operatorLists.get(which).getOperatingHouseholds();
                                        samplingInformation.setOperatingHouseholdId(operatorLists.get(which).getPkId());

                                    }
                                }).create();
                                dialogs.show();
                                // 通过Activity类中的getWindowManager()方法获取窗口管理，再调用getDefaultDisplay()方法获取获取Display对象
                                Display display = getActivity().getWindowManager().getDefaultDisplay();
                                // 方法一(推荐使用)使用Point来保存屏幕宽、高两个数据
                                Point outSize = new Point();
                                // 通过Display对象获取屏幕宽、高数据并保存到Point对象中
                                display.getSize(outSize);
                                // 从Point对象中获取宽、高
                                int x = (new Double(outSize.x*0.9)).intValue();
                                int y = (new Double(outSize.y*0.9)).intValue();

                                dialogs.getWindow().setLayout(x,y);
                                //弹出对话框时需要点击输入框才能弹出软键盘
                                dialogs.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                                dialogs.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(13);
                                Drawable dr = getActivity().getResources().getDrawable(R.drawable.login_btn_selector); //取得图片资源
                                dialogs.getButton(AlertDialog.BUTTON_POSITIVE).setBackground(dr);
                                LinearLayout.LayoutParams PositiveButton =
                                        (LinearLayout.LayoutParams)  dialogs.getButton(DialogInterface.BUTTON_POSITIVE).getLayoutParams();
                                PositiveButton.height = (new Double(outSize.x*0.12)).intValue();
                                PositiveButton.width = (new Double(outSize.x*0.35)).intValue();
                                //设置文字居中
                                PositiveButton.gravity = Gravity.CENTER;
                                PositiveButton.setMargins(new Double(outSize.x-outSize.x*0.3).intValue()/2,
                                        20, new Double(outSize.x-outSize.x*0.3).intValue()/2, 20);
                                dialogs.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

                                    @Override
                                    public void onClick(View v) {
                                        if (!TextUtils.isEmpty(edit.getText().toString())) {
                                            ArrayList<String> strlist = new ArrayList<String>();
                                            List<tanchubean> list=new ArrayList<>();
                                            ArrayList<OperatingBean> operatorList1 = new ArrayList<OperatingBean>();
                                            for (int i = 0; i < operatorLists.size(); i++) {
                                                if(operatorLists.get(i).getOperatingHouseholds().indexOf(edit.getText().toString()) != -1||operatorLists.get(i).getBoothNumber().indexOf(edit.getText().toString()) != -1){
                                                    strlist.add(operatorLists.get(i).getOperatingHouseholds()+"("+operatorLists.get(i).getBoothNumber()+")");
                                                    operatorList1.add(operatorLists.get(i));
                                                    tanchubean<String> list1=new tanchubean();
                                                    list1.setName(operatorLists.get(i).getOperatingHouseholds()+"("+operatorLists.get(i).getBoothNumber()+")");
                                                    list.add(list1);
                                                }
                                            }
                                            ListViewItemAdapter adapter = new ListViewItemAdapter(getContext(),list);
                                            String s[] = (String[]) strlist.toArray(new String[strlist.size()]);
                                            AlertDialog.Builder dialog = new AlertDialog.Builder(getContext())
                                                    .setAdapter(adapter, new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.dismiss();
                                                            dialogs.dismiss();
                                                            TextView t = view.findViewById(R.id.listview_text_data);
                                                            t.setTextColor(Color.BLACK);
                                                            t.setText(operatorList1.get(which).getOperatingHouseholds());
                                                            jingyinghu=operatorList1.get(which).getOperatingHouseholds();
                                                            samplingInformation.setOperatingHouseholdId(operatorList1.get(which).getPkId());

                                                        }
                                                    });
                                            dialog.create().show();

                                        }

                                    }
                                });

                            }
                            }else{
                                Toast.makeText(getContext(),"请先选择样品类别",Toast.LENGTH_LONG).show();
                            }
                        }else {
                            Toast.makeText(getContext(),"请先选择市场名称",Toast.LENGTH_LONG).show();
                        }
                    }break;
                    case 1:{

                        if (typelist.getData()!=null) {
                            List<tanchubean> list=new ArrayList<>();
                            String s[]=new String[typelist.getData().size()];
                            for (int i=0;i<typelist.getData().size();i++)
                            {
                                s[i]=typelist.getData().get(i).getTypeName();
                                tanchubean<String> list1=new tanchubean();
                                list1.setName(typelist.getData().get(i).getTypeName());
                                list.add(list1);
                            }
                            ListViewItemAdapter adapter = new ListViewItemAdapter(getContext(),list);
                            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                            builder.setTitle("请选择样品类别");
                            builder.setIcon(R.mipmap.xuanze);
                            builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();

                                    TextView t = view.findViewById(R.id.listview_text_data);
                                    t.setText(typelist.getData().get(which).getTypeName());
                                    t.setTextColor(Color.BLACK);
                                    samplingInformation.setSampleType(typelist.getData().get(which).getTypeId());
                                     smilt=typelist.getData().get(which).getTypeId();
                                     leibie=typelist.getData().get(which).getTypeName();
                                    typelistname=typelist.getData().get(which).getList();
                                    SimpleRequest s1=new SimpleRequest();
                                    s1.setAccountPkId(BaseApplication.getAccount().getPkId());
                                    s1.setSamplingTypePkId(typelist.getData().get(which).getTypeId());
                                    samplePresenter.getOperatingResponseInfo(s1);
                                    ArrayList<TypeList> typeLists = new ArrayList<>();
                                    for (int i = 0; i < typelistDeTypeAndName.getData().size(); i++) {
                                        if (smilt.equals(typelistDeTypeAndName.getData().get(i).getSamplType())) {
                                            typeLists.add(typelistDeTypeAndName.getData().get(i));
                                        }
                                    }
                                   if(typeLists.size()!=0){

                                          typelistnametDeTypeAndName=typeLists.get(0).getList();
                                          jiancexiangmu = typeLists.get(0).getTypeName();
                                          samplingRequset.setDeTypeId(typeLists.get(0).getTypeId());
                                          jiancefangfa=typelistnametDeTypeAndName.get(0).getName();

                                          samplingRequset.setDeMethoodPkID(typelistnametDeTypeAndName.get(0).getNameId());

                                   }
                                    leibiebiaoshi=1;
                                    if(leibiebiaoshi==1){
                                        initListView(3);
                                    }
                                }
                            });
                            builder.create().show();

                        }

                    }break;
                    case 3:{
                        xiangpinmingcheng=null;
                        LayoutInflater inflater = LayoutInflater.from(getContext());
                        View layout = inflater.inflate(R.layout.edit_select, null);
                        View list = inflater.inflate(R.layout.dialog_listview, null);
                        final EditText edit = (EditText)layout.findViewById(R.id.listview_edit_data);
                        final ListView listdata = (ListView) list.findViewById(R.id.dialog_list);

                        List<String> lists = new ArrayList<String>();
                        for (int i=0;i<typelist.getData().size();i++)
                        {
                            lists.add(typelist.getData().get(i).getTypeName());

                        }
                        List<tanchubean> list3=new ArrayList<>();
                        //listdata.setAdapter(lists);
                        if (typelistname.size()!=0) {

                            String s[]=new String[typelistname.size()];
                            for (int i=0;i<typelistname.size();i++)
                            {
                                s[i]=typelistname.get(i).getName();
                                tanchubean<String> list1=new tanchubean();
                                list1.setName(typelistname.get(i).getName());
                                list3.add(list1);
                            }

                            ListViewItemAdapter adapter = new ListViewItemAdapter(getContext(),list3);
                            AlertDialog dialogs = new AlertDialog.Builder(getContext())

                                    .setCustomTitle(layout)
                                    //.setView(list)
                                    .setNegativeButton("添加新采样名称",new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            typelistAdd=typelist;
                                            Log.d("2333", "qqqq");
                                            Intent intent = new Intent(getActivity(), AddTypeActivity.class);
                                            startActivity(intent);

                                        }
                                    })
                                    .setPositiveButton("搜索采样名称",null)
                                    .setAdapter(adapter, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                            TextView t = view.findViewById(R.id.listview_text_data);
                                            t.setText(typelistname.get(which).getName());
                                            xiangpinmingcheng=typelistname.get(which).getName();
                                            t.setTextColor(Color.BLACK);
                                            samplingInformation.setSampleName(typelistname.get(which).getNameId());

                                        }
                                    })
                                    .create();
                            dialogs.show();
                            // 通过Activity类中的getWindowManager()方法获取窗口管理，再调用getDefaultDisplay()方法获取获取Display对象
                            Display display = getActivity().getWindowManager().getDefaultDisplay();
                            // 方法一(推荐使用)使用Point来保存屏幕宽、高两个数据
                            Point outSize = new Point();
                            // 通过Display对象获取屏幕宽、高数据并保存到Point对象中
                            display.getSize(outSize);
                            // 从Point对象中获取宽、高
                            int x = (new Double(outSize.x*0.9)).intValue();
                            int y = (new Double(outSize.y*0.9)).intValue();

                            dialogs.getWindow().setLayout(x,y);
                            //弹出对话框时需要点击输入框才能弹出软键盘
                            dialogs.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                            dialogs.getButton(DialogInterface.BUTTON_NEGATIVE).setTextSize(13);
                            dialogs.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(13);
                            Drawable dr = getActivity().getResources().getDrawable(R.drawable.login_btn_selector); //取得图片资源
                            dialogs.getButton(DialogInterface.BUTTON_NEGATIVE).setBackground(dr);
                            dialogs.getButton(AlertDialog.BUTTON_POSITIVE).setBackground(dr);
                            LinearLayout.LayoutParams NegativeButton =
                                    (LinearLayout.LayoutParams)  dialogs.getButton(DialogInterface.BUTTON_NEGATIVE).getLayoutParams();
                            NegativeButton.height = (new Double(outSize.x*0.12)).intValue();
                            NegativeButton.width = (new Double(outSize.x*0.3)).intValue();
                            NegativeButton.setMargins(0, 20, 40, 20);
                            //设置文字居中
                            NegativeButton.gravity = Gravity.CENTER;
                            LinearLayout.LayoutParams PositiveButton =
                                    (LinearLayout.LayoutParams)  dialogs.getButton(DialogInterface.BUTTON_POSITIVE).getLayoutParams();
                            PositiveButton.height = (new Double(outSize.x*0.12)).intValue();
                            PositiveButton.width = (new Double(outSize.x*0.3)).intValue();
                            //设置文字居中
                            PositiveButton.gravity = Gravity.CENTER;
                            PositiveButton.setMargins(20, 20, 40, 20);

                            dialogs.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    if (!TextUtils.isEmpty(edit.getText().toString())) {
                                        List<tanchubean> list3=new ArrayList<>();
                                        ArrayList<String> strlist = new ArrayList<String>();
                                        ArrayList<TypeListItem> operatorLists = new ArrayList<TypeListItem>();
                                        for (int i = 0; i < typelistname.size(); i++) {
                                            if(typelistname.get(i).getName().indexOf(edit.getText().toString()) != -1){
            //                                System.out.println("菜市场id:"+operatorList.get(i).getMarketId());
            //                                System.out.println("菜市场id:"+num);
            //                                System.out.println("人员名:"+operatorList.get(i).getOperatingHouseholds());
                                                strlist.add(typelistname.get(i).getName());
                                                operatorLists.add(typelistname.get(i));
                                                tanchubean<String> list1=new tanchubean();
                                                list1.setName(typelistname.get(i).getName());
                                                list3.add(list1);
                                            }
                                        }
                                        ListViewItemAdapter adapter = new ListViewItemAdapter(getContext(),list3);
                                        String s[] = (String[]) strlist.toArray(new String[strlist.size()]);
                                        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext())
                                                .setAdapter(adapter, new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.dismiss();
                                                        dialogs.dismiss();
                                                        TextView t = view.findViewById(R.id.listview_text_data);
                                                        t.setText(operatorLists.get(which).getName());
                                                        xiangpinmingcheng=operatorLists.get(which).getName();
                                                        t.setTextColor(Color.BLACK);
                                                        samplingInformation.setSampleName(operatorLists.get(which).getNameId());


                                                    }
                                                });
                                        dialog.create().show();

                                    }

                                }
                            });


                        }else {
                            Toast.makeText(getContext(),"请先选择样品类别",Toast.LENGTH_LONG).show();
                        }
                    }break;

                    case 4:{
//                final String items[] = {"A", "B", "C"};
//                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
//                builder.setTitle("请选择市场");
//                builder.setIcon(R.mipmap.ic_launcher);
//                builder.setItems(items, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        TextView t=view.findViewById(R.id.listview_text_data);
//                        t.setText(items[which]);
//                    }
//                });
//                builder.create().show();
                        if(smilt!=null){
                            if (typelistDeTypeAndName!=null) {
                                List<tanchubean> list=new ArrayList<>();
                                //Log.d("请选择检测类型",typelistDeTypeAndName.getData().size()+"");
                                ArrayList<String> strlist = new ArrayList<String>();
                                ArrayList<TypeList> typeLists=new ArrayList<>();
                                for (int i = 0; i < typelistDeTypeAndName.getData().size(); i++) {
                                    if(smilt.equals(typelistDeTypeAndName.getData().get(i).getSamplType())){
                                        strlist.add(typelistDeTypeAndName.getData().get(i).getTypeName());
                                        typeLists.add(typelistDeTypeAndName.getData().get(i));
                                        tanchubean<String> list1=new tanchubean();
                                        list1.setName(typelistDeTypeAndName.getData().get(i).getTypeName());
                                        list.add(list1);


                                    }
                                }
                                ListViewItemAdapter adapter = new ListViewItemAdapter(getContext(),list);
                                String s[] = (String[]) strlist.toArray(new String[strlist.size()]);
                                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                                builder.setTitle("请选择检测项目");
                                builder.setIcon(R.mipmap.xuanze);
                                builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();

                                        TextView t = view.findViewById(R.id.listview_text_data);
                                        t.setText(typeLists.get(which).getTypeName());
                                        jiancexiangmu=typeLists.get(which).getTypeName();
                                        //System.out.println(typeLists.get(which).getList().size());
//                                        for(int i=0;i<typeLists.get(which).getList().size();i++){
//                                            TypeListItem typeListItem = new TypeListItem();
//                                            typeListItem.setNameId(typeLists.get(which).getList().get(i).getNameId());
//                                            typeListItem.setName(typeLists.get(which).getList().get(i).getName());
//                                            typelistnametDeTypeAndName.add(typeListItem);
//                                        }

                                        typelistnametDeTypeAndName=typeLists.get(which).getList();
                                      if(typeLists.get(which).getList().size()!=0){

                                          jiancefangfa=typelistnametDeTypeAndName.get(0).getName();
                                          samplingRequset.setDeMethoodPkID(typelistnametDeTypeAndName.get(0).getNameId());
                                      }else{
                                          jiancefangfa="请选择";
                                          samplingRequset.setDeMethoodPkID(null);

                                      }

                                        t.setTextColor(Color.BLACK);
                                        samplingRequset.setDeTypeId(typeLists.get(which).getTypeId());
                                        jiancebiaoshi=1;
                                        if(jiancebiaoshi==1){
                                            initListView(4);
                                        }
                                    }
                                });
                                builder.create().show();
                            }
                        }else{
                            Toast.makeText(getContext(),"请先选择样品类别",Toast.LENGTH_LONG).show();
                        }
                    }break;
                    case 5:{
                        if(typelistnametDeTypeAndName!=null){

                                List<tanchubean> list=new ArrayList<>();

                                for (int i=0;i<typelistnametDeTypeAndName.size();i++)
                                {

                                    tanchubean<String> list1=new tanchubean();
                                    list1.setName(typelistnametDeTypeAndName.get(i).getName());
                                    list.add(list1);
                                }
                                ListViewItemAdapter adapter = new ListViewItemAdapter(getContext(),list);
                                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                                builder.setTitle("请选择检测方法");
                                builder.setIcon(R.mipmap.xuanze);
                                builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        TextView t = view.findViewById(R.id.listview_text_data);
                                        t.setText(list.get(which).getName());
                                        jiancefangfa=list.get(which).getName();
                                        t.setTextColor(Color.BLACK);
                                        samplingRequset.setDeMethoodPkID(typelistnametDeTypeAndName.get(which).getNameId());

                                    }
                                });
                                builder.create().show();

                        }else{
                            Toast.makeText(getContext(),"请先选择检测项目",Toast.LENGTH_LONG).show();
                        }

                    }break;
                }
            }
        });
        initUI();
        addPlus();
//        imagelistView.setAdapter(new ListviewRichTextAdapter(list,getContext()));
    }




    public  void initRequest(){
        SimpleRequest s=new SimpleRequest();
        s.setAccountPkId(BaseApplication.getAccount().getPkId());
        samplePresenter.getMarketResponseInfo(s);
        samplePresenter.getOperatingResponseInfo(s);
        samplePresenter.getSamplingNameResponseInfo(s);
        samplePresenter.getDeTypeAndNameResponseInfo(s);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (selectPhoto != null) {
            String photoPath = selectPhoto.getPhotoResultPath(requestCode, resultCode, data);
            if (!TextUtils.isEmpty(photoPath)) {
                commandPhoto.showGridPhoto(photoPath);
                //System.out.println("1111111111111111111111"+photoPath);
            }
        }
    }
    //wxs添加
    protected Context mCtx;
    protected Activity theActivity;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //wxs添加
        mCtx = context;
        theActivity=(Activity) context;
        Application.theLocContext=context;
        Application.theActivity=getActivity();
        //        getActivity().getSupportFragmentManager().    (SampleFragment.newInstance());
    }

    @Override
    public void getMarketList(Object resultData) {

        CallbackData callbackData=(CallbackData<List<Market>>)resultData;
        marketList=(List<Market>)callbackData.getData();
//      final    String items[] =
//         (String[]) list.toArray();

//            List list= list.toArray();
//            items= (String[]) list.toArray();
    }

    @Override
    public void getOperatorList(Object resultData) {
        CallbackData callbackData=(CallbackData<List<OperatingBean>>)resultData;
        operatorList=(List<OperatingBean>)callbackData.getData();


    }

    @Override
    public void getSamplingName(Object resultData) {
        typelist=(CallbackData<List<TypeList>> )resultData;
        //     Log.d("typelist",typelistDeTypeAndName.getData().get(0).getList().get(0).getName()+"");
    }

    @Override
    public void getDeTypeAndName(Object resultData) {
        typelistDeTypeAndName=(CallbackData<List<TypeList>> )resultData;
    }

    @Override
    public void getInsertSamplingResponseInfo(Object resultData) {
        SampleCallbackData callbackData=(SampleCallbackData)resultData;
        Log.d("getAlertMessage", callbackData.getAlertMessage()+callbackData.getState());
        if (callbackData.getState()==1)
        {
            SamplingViewModel model = ViewModelProviders.of(getActivity()).get(SamplingViewModel.class);
            if (model!=null)
            {
                model.setData(samplingInformation);
                model.setSamplingPkId(callbackData.getSamplingPkId());
            }
            if(jumpid==1){

                    cunchu.setJingyinghuname(jingyinghu);

                    cunchu.setJingyinghuname(jiancefangfa);

                    cunchu.setJiancetypename(jiancexiangmu);

                    cunchu.setJiancefangfaname(jiancefangfa);

                    cunchu.setYangpinname(xiangpinmingcheng);

                    cunchu.setYangpintypename(leibie);

                cunchu.setKEY(0);
                cunchu.setBiaoshi(0);
                cunchu.setJingyinghuid(samplingInformation.getOperatingHouseholdId());

                cunchu.setJiancefangfaid(samplingRequset.getDeMethoodPkID());

                cunchu.setJiancetypeid(samplingRequset.getDeTypeId());

                cunchu.setYangpinid(samplingInformation.getSampleAccountId());

                cunchu.setYangpintypeid(samplingInformation.getSampleType());

                cunchu.setShichangid(num);
                cunchu.setShichangname(shichang);
                yx=true;
                getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.container, LabelPrintedFragment.newInstance())
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                        .addToBackStack(null)
                        .commit();

//                outState.putString("KEY", "4");
//                outState.putString("jingyinghuid", samplingInformation.getOperatingHouseholdId());
//                outState.putString("jingyinghuname", jingyinghu);
//                outState.putString("jiancefangfaid", samplingRequset.getDeMethoodPkID());
//                outState.putString("jiancefangfaname", jiancefangfa);
//                outState.putString("jiancetypeid", samplingRequset.getDeTypeId());
//                outState.putString("jiancetypename", jiancexiangmu);
//                outState.putString("yangpinid", samplingInformation.getSampleAccountId());
//                outState.putString("yangpinname",xiangpinmingcheng );
//                outState.putString("yangpintypeid", samplingInformation.getSampleType());
//                outState.putString("yangpintypename",leibie );
//                outState.putString("shichangid", num);
//                outState.putString("shichangname", shichang);
            }

        }else if(callbackData.getState()==200){
            Toast.makeText(getContext(),callbackData.getAlertMessage(),Toast.LENGTH_LONG).show();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //wxs添加
        mCtx =null;
        locationService.stop();
        locationService.unregisterListener(mListener);
        //locationService=null;

        Log.d("onDetach","onDestroy");
    }

    @Override
    public void onError(String result) {
        Log.d("getAlertMessage",result);
    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        // 获取照片返回
//        if (selectPhoto != null) {
//            String photoPath = selectPhoto.getPhotoResultPath(requestCode, resultCode, data);
//            if (!TextUtils.isEmpty(photoPath)) {
//                commandPhoto.showGridPhoto(photoPath);
//            }
//        }
//    }


    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        /**
         * 定位请求回调函数
         *
         * @param location 定位结果
         */
        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                //System.out.println("进来了"+location);
                int tag = 1;
                StringBuffer sb = new StringBuffer(256);
                //wxs添加
                if(getActivity()!=null){
                    theActivity=getActivity();
                }

                //sb.append("time : ");
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */
                //sb.append(location.getTime());
                //sb.append("\nlocType : ");// 定位类型
                //sb.append(location.getLocType());
                //sb.append("\nlocType description : ");// *****对应的定位类型说明*****
                //sb.append(location.getLocTypeDescription());
                //sb.append("\nlatitude : ");// 纬度
                //wxs修改
                String theWeidu=String.valueOf(location.getLatitude());
                if(theWeidu!=null && theWeidu.indexOf("E")<0) {
                    weidu = theWeidu;
                }
                //sb.append("\nlongtitude : ");// 经度
                String theJingdu=String.valueOf(location.getLongitude());
                if(theWeidu!=null && theWeidu.indexOf("E")<0) {
                    jingdu = theJingdu;
                }
                //jingdu=String.valueOf(location.getLongitude());
                //sb.append("\nradius : ");// 半径
                //sb.append(location.getRadius());
                //sb.append("\nCountryCode : ");// 国家码
                //sb.append(location.getCountryCode());
                //sb.append("\nProvince : ");// 获取省份
                //sb.append(location.getProvince());
                //sb.append("\nCountry : ");// 国家名称
                //sb.append(location.getCountry());
                //sb.append("\ncitycode : ");// 城市编码
                //sb.append(location.getCityCode());
                //sb.append("\ncity : ");// 城市
                //sb.append(location.getCity());
                //sb.append("\nDistrict : ");// 区
                //sb.append(location.getDistrict());
                //sb.append("\nTown : ");// 获取镇信息
                //sb.append(location.getTown());
                //sb.append("\nStreet : ");// 街道
                //sb.append(location.getStreet());
                //sb.append("\naddr : \n");// 地址信息
                //wxs修改
                String theLocAddress=location.getAddrStr();
                if(theLocAddress!=null) {
                    xiangxidizhi = theLocAddress;
                }
                //sb.append("\nStreetNumber : ");// 获取街道号码
                //sb.append(location.getStreetNumber());
                //sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果*****
                //sb.append(location.getUserIndoorState());
                //sb.append("\nDirection(not all devices have value): ");
                //sb.append(location.getDirection());// 方向
                //sb.append("\nlocationdescribe: ");
                //sb.append(location.getLocationDescribe());// 位置语义化信息
                //sb.append("\nPoi: ");// POI信息
                if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                    for (int i = 0; i < location.getPoiList().size(); i++) {
                        Poi poi = (Poi) location.getPoiList().get(i);
                        xiangxidizhi+=poi.getName();
                        break;
                    }
                    xiangxidizhi=xiangxidizhi.replace("中国","");
                }
                // if (location.getPoiRegion() != null) {
                //     sb.append("PoiRegion: ");// 返回定位位置相对poi的位置关系，仅在开发者设置需要POI信息时才会返回，在网络不通或无法获取时有可能返回null
                //     PoiRegion poiRegion = location.getPoiRegion();
                //     sb.append("DerectionDesc:"); // 获取POIREGION的位置关系，ex:"内"
                //     sb.append(poiRegion.getDerectionDesc() + "; ");
                //     sb.append("Name:"); // 获取POIREGION的名字字符串
                //     sb.append(poiRegion.getName() + "; ");
                //     sb.append("Tags:"); // 获取POIREGION的类型
                //     sb.append(poiRegion.getTags() + "; ");
                //     sb.append("\nSDK版本: ");
                // }
                //sb.append(locationService.getSDKVersion()); // 获取SDK版本
                //if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                //    sb.append("\nspeed : ");
                //    sb.append(location.getSpeed());// 速度 单位：km/h
                //    sb.append("\nsatellite : ");
                //    sb.append(location.getSatelliteNumber());// 卫星数目
                //    sb.append("\nheight : ");
                //    sb.append(location.getAltitude());// 海拔高度 单位：米
                //    sb.append("\ngps status : ");
                //    sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
                //    sb.append("\ndescribe : ");
                //    sb.append("gps定位成功");
                // } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                //     // 运营商信息
                //     if (location.hasAltitude()) {// *****如果有海拔高度*****
                //         sb.append("\nheight : ");
                //         sb.append(location.getAltitude());// 单位：米
                //     }
                //     sb.append("\noperationers : ");// 运营商信息
                //     sb.append(location.getOperators());
                //     sb.append("\ndescribe : ");
                //     sb.append("网络定位成功");
                // } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                //     sb.append("\ndescribe : ");
                //     sb.append("离线定位成功，离线定位结果也是有效的");
                // } else if (location.getLocType() == BDLocation.TypeServerError) {
                //     sb.append("\ndescribe : ");
                //     sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                // } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                //     sb.append("\ndescribe : ");
                //     sb.append("网络不同导致定位失败，请检查网络是否通畅");
                // } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                //     sb.append("\ndescribe : ");
                //     sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                // }
                //wxs增加判定
                if(theLocAddress!=null) {
                    updateGps();
                }
            }
        }
    };









}
